package com.futao.springbootlearn20220224.redis.queue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author futao@gmail.com
 * @date 2022/4/12
 */
@Slf4j
@RequestMapping("queue-demo")
// @RestController
public class QueueDemo {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    String key = "sb:queue:demo";

    @GetMapping("/producer")
    public Long producer(@RequestParam("value") String value) {
        return stringRedisTemplate.opsForList().leftPush(key, value);
    }

    // @PostConstruct
    public void consumer() {
        new Thread(() -> {
            while (true) {
                String value = stringRedisTemplate.opsForList().rightPop(key);
                log.info("value:{}", value);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @PostConstruct
    public void consumer2() {
        new Thread(() -> {
            while (true) {
                List<byte[]> bytes = redisConnectionFactory.getClusterConnection().bRPop(0, key.getBytes(StandardCharsets.UTF_8));
                for (byte[] aByte : bytes) {
                    String vs = new String(aByte);
                    log.info("value:{}", vs);
                }
            }
        }).start();
    }

}
